<?php
/**
 * Created by 项目.
 * User: xuguopeng
 * Date: 6/6/21
 * Time: 9:36 AM
 */

namespace app\api\controller\v1;


use app\api\model\Product as ProductModel;
use app\api\model\ProductOrder;
use app\api\model\ProductOrderContent;
use app\api\model\Store;
use app\api\model\StoreUser as StoreUserModel;
use app\api\model\TeamUser as TeamUserModel;
use app\api\model\UserMoney as UserMoneyModel;
use app\api\model\User as UserModel;
use app\api\model\Team as TeamModel;
use app\api\model\ProductOrderContent as ProductOrderContentModel;
use app\api\model\ProductOrder as ProductOrderModel;
use app\api\model\UserInvitation;

class EChart
{
    // 总量
    public function getAll()
    {
        $sale = ProductOrder::where('status','gt',1)->sum('actual_price');
        $whereSelf[] = ['status','gt',1];
        $volume = ProductOrder::where($whereSelf)->count();
        $old_user_num = UserModel::where('new_type',2)
            ->where('status',3)->count();
        $userlist =  UserModel::where('new_type',1)
            ->select()->toArray();
        $ids = array_column($userlist,'id');
        $new_user_num = ProductOrder::field('user_id')
            ->where('user_id','in',$ids)
            ->where('status','gt',1)
            ->group('user_id')
            ->count();
        $all_user_num = UserModel::count();
        return [
            'sale' => $sale,
            'volume' => $volume,
            'old_user_num' => $old_user_num,
            'new_user_num' => $new_user_num,
            'all_user_num' => $all_user_num
        ];
    }

    // 店铺销售额排行
    public function getStoreSale()
    {
        $stores = Store::order('order_sort decs')->select()->toArray();
        foreach ($stores as $k=>$v){
            $whereThree = [];
            $whereThree[] = ['store_id','eq',$stores[$k]['id']];
            $whereThree[] = ['status','gt',1];
            $sale = ProductOrder::where($whereThree)
                ->sum('actual_price');
            $stores[$k]['sale'] = $sale;
        }
        if(count($stores) > 0) {
            $stores = $this->arraySort($stores,'sale');
        }
        return $stores;
    }

    // 店铺成交量排行
    public function getStoreVolume()
    {
        $stores = Store::order('order_sort decs')->select()->toArray();
        foreach ($stores as $k=>$v){
            $stores[$k]['volume'] = ProductOrder::where('store_id',$v['id'])
                ->where('status','gt',1)
                ->count();
        }
        if(count($stores) > 0) {
            $stores = $this->arraySort($stores,'volume');
        }
        return $stores;
    }

    // 店铺新客数排行
    public function getStoreNewUserNum()
    {
        $store  = Store::order('id desc')->select()->toArray();
        foreach ($store as $k => $v){
            $userlist =  UserModel::where('store_id',$v['id'])
                ->where('new_type',1)
                ->select()->toArray();
            $ids = array_column($userlist,'id');
            $productordercount = ProductOrder::field('user_id')
                ->where('user_id','in',$ids)
                ->where('status','gt',1)
                ->group('user_id')
                ->count();
            $store[$k]['new_user_num'] = $productordercount;
        }
        if(count($store) > 0) {
            $store = $this->arraySort($store,'new_user_num');
        }
        return $store;
    }

    // 店铺旧客数排行
    public function getStoreOldUserNum()
    {
        $stores = Store::order('order_sort decs')->select()->toArray();
        foreach ($stores as $k=>$v){
            $stores[$k]['old_user_num'] = UserModel::where('new_type',2)
                ->where('store_id','eq',$v['id'])
                ->where('status',3)->count();
        }
        return $stores;
    }

    // 员工销售额
    public function getStoreUserSale()
    {
        $storesUser = StoreUserModel::with('store,user')->order('id decs')->select()->toArray();
        foreach ($storesUser as $k=>$v){
            if($v['type'] == 1) {
                $storesUser[$k]['type_name'] = '店长';
            } elseif($v['type'] == 2) {
                $storesUser[$k]['type_name'] = '组长';
            } elseif($v['type'] == 3) {
                $storesUser[$k]['type_name'] = '店员';
            }
            $whereTwo=[];
            $whereTwo[] = ['inviter','eq',$v['id']];
            $whereTwo[] = ['type','eq',2];

            $userInvitation = UserInvitation::where($whereTwo)->select()->toArray();
            $ids = array_column($userInvitation,'invitee');

            $whereThree=[];
            $whereThree[] = ['user_id','in',$ids];
            $whereThree[] = ['status','gt',1];
            $sale = ProductOrder::where($whereThree)
                ->sum('actual_price');

            $whereFour=[];
            $whereFour[] = ['user_id','eq',$v['user']['id']];
            $whereFour[] = ['status','gt',1];
            $sale_one = ProductOrder::where($whereFour)
                ->sum('actual_price');
            $storesUser[$k]['sale'] = $sale + $sale_one;
        }
        if(count($storesUser) > 0) {
            $storesUser = $this->arraySort($storesUser,'sale');
        }
        return $storesUser;
    }

    // 团销售额
    public function getTeamSale()
    {
        $team = TeamModel::order('id decs')->select()->toArray();
        foreach ($team as $k=>$v){
            $teamUsers = TeamUserModel::where('team_id',$v['id'])->with('user')->select()->toArray();
            $team_user_ids = array_column($teamUsers,'id');
            $whereTwo[] = ['inviter','in',$team_user_ids];
            $whereTwo[] = ['type','eq',3];
            $userInvitation = UserInvitation::where($whereTwo)->select()->toArray();
            $ids = array_column($userInvitation,'invitee');
            $whereThree[] = ['user_id','in',$ids];
            $whereThree[] = ['status','gt',1];
            $sale = ProductOrder::where($whereThree)
                ->sum('actual_price');
            $team[$k]['sale'] = $sale;
        }
        return $team;
    }

    // 团收入
    public function getTeamMoney()
    {
        $team = TeamModel::order('id decs')->select()->toArray();
        foreach ($team as $k=>$v){
            $teamUsers = TeamUserModel::where('team_id',$v['id'])->with('user')->select()->toArray();
            $team_user_ids = array_column($teamUsers,'id');
            $whereTwo[] = ['team_user_id','in',$team_user_ids];
            $whereTwo[] = ['user_type','eq',3];
            $team[$k]['user_money'] = UserMoneyModel::where($whereTwo)->sum('money');
        }
        return $team;
    }

    // 团员销售额
    public function getTeamUserSale()
    {
        $teamUser = TeamUserModel::with('team,user')->order('id decs')->select()->toArray();
        foreach ($teamUser as $k=>$v){
            if($v['type'] == 1) {
                $teamUser[$k]['type_name'] = '团长';
            } elseif($v['type'] == 2) {
                $teamUser[$k]['type_name'] = '团员';
            }
            $whereTwo[] = ['inviter','in',$v['id']];
            $whereTwo[] = ['type','eq',3];
            $userInvitation = UserInvitation::where($whereTwo)->select()->toArray();
            $ids = array_column($userInvitation,'invitee');
            $whereThree[] = ['user_id','in',$ids];
            $whereThree[] = ['status','gt',1];
            $sale = ProductOrder::where($whereThree)
                ->sum('actual_price');
            $whereFour[] = ['user_id','eq',$v['user']['id']];
            $whereFour[] = ['status','gt',1];
            $sale_one = ProductOrder::where($whereFour)
                ->sum('actual_price');
            $teamUser[$k]['sale'] = $sale + $sale_one;
        }
        return $teamUser;
    }

    //产品销量排行
    public function getProductContentList(){
        $voList = ProductOrderContentModel::field("count(*) as count,product_id")
            ->group("product_id")
            ->order("count desc")
            ->select();
        $result = [];
        $num = 0;
        foreach ($voList as $item=>$info){
            $proinfo = ProductModel::with('img,store')->where('id',$info['product_id'])->find();
            if($proinfo!=null){
                $proinfo['count'] = $info['count'];
                $result[$num] = $proinfo;
                $num++;
            }

        }
        return $result;
    }

    //员工收入排行
    public function getStoreUserinvite_money(){
        $usermoneylist =  UserMoneyModel::field(" SUM(money) as summoney,user_id")
            ->where("user_type",'2')
            ->group("user_id")
            ->order("summoney desc")
            ->select();

        $result = [];
        $num = 0;
        foreach ($usermoneylist as $item=>$info){
            $userinfo = UserModel::where("id",$info['user_id'])->find();
            if($userinfo!=null){
                $userinfo['summoney'] = $info['summoney'];

                if($userinfo['type'] == 1) {
                    $userinfo['type_name'] = '店长';
                } elseif($userinfo['type'] == 2) {
                    $userinfo['type_name'] = '组长';
                } elseif($userinfo['type'] == 3) {
                    $userinfo['type_name'] = '店员';
                }

                $storeuser = StoreUserModel::where('user_id',$info['user_id'])->find();

                if($storeuser!=null){
                    $store = Store::where('id',$storeuser['store_id'])->find();
                    $userinfo['storeuser'] = $storeuser;
                    $userinfo['store'] = $store;

                    $result[$num] = $userinfo;
                    $num++;
                }
            }
        }
        return $result;
    }


    // 员工成交量排行
    public function getstoreuserproductnum()
    {
        $storesUser = StoreUserModel::with('store,user')->order('id decs')->select()->toArray();
        foreach ($storesUser as $k=>$v){
            if($v['type'] == 1) {
                $storesUser[$k]['type_name'] = '店长';
            } elseif($v['type'] == 2) {
                $storesUser[$k]['type_name'] = '组长';
            } elseif($v['type'] == 3) {
                $storesUser[$k]['type_name'] = '店员';
            }
            $userinv = UserInvitation::field("invitee")->where('inviter',$v['id'])->select()->toArray();
            $ids = array_column($userinv,'invitee');
            $storesUser[$k]['userinvs'] = ProductOrder::where('user_id','in',$ids)->count();
        }
        if(count($storesUser) > 0) {
            $storesUser = $this->arraySort($storesUser,'userinvs');
        }
        return $storesUser;
    }


    // 员工成交量排行
    public function getstoreuserproductnumbak()
    {

    }


    //成交动态
    public function getnewproductorder(){
        $newproductuser = ProductOrderContent::with('product,user')
            ->where('status',2)
            ->order('update_time desc')
            ->limit('0,10')
            ->select()
            ->toArray();
        $result = [];
        $num = 0;
        foreach($newproductuser as $k => $v){
            $newproductuser[$k]['store'] = Store::where('id',$v['user']['store_id'])->find();
            $newproductuser[$k]['productorder']  = ProductOrderModel::where('id',$v['product_order_id'])->find();
            $invuser = UserInvitation::where('invitee',$v['user_id'])->with('user')->find();
            if($invuser==null){
                $newproductuser[$k]['inviteeuser']='未知' ;
            }elseif ($invuser['type']==2){
                $newproductuser[$k]['inviteeuser']= '员工' ;
            }elseif ($invuser['type']==3){
                $newproductuser[$k]['inviteeuser']= '团员' ;
            }elseif ($invuser['type']==1){
                $newproductuser[$k]['inviteeuser']= '顾客' ;
            }
            if($newproductuser[$k]['user']!=null&&$newproductuser[$k]['store']!=null)
            {
                $newproductuser[$k]['show_update_time'] = substr($v['update_time'],11,18);
                $result[$num] = $newproductuser[$k];
                $num++;
            }

        }
        return $result;
    }

    /**
     * 二维数组根据某个字段排序
     * @param array $array 要排序的数组
     * @param string $keys   要排序的键字段
     * @param string $sort  排序类型  SORT_ASC     SORT_DESC
     * @return array 排序后的数组
     */
    public function arraySort($array, $keys, $sort = SORT_DESC) {
        $keysValue = [];
        foreach ($array as $k => $v) {
            $keysValue[$k] = $v[$keys];
        }
        array_multisort($keysValue, $sort, $array);
        return $array;
    }
}